var user = require('../schema/user')
var connectDB = require('../connectdb')
var mongoose = require('mongoose')
var express = require('express');
var router = express.Router();
var formidable = require('formidable')
var hat = require('hat')
var rack = hat.rack()
var path = require('path');
var fs = require('fs');
connectDB(mongoose)

exports.checkToken = function (req, res, next) {
    var token = req.headers.token
    user.findOne({ 'token': token }, function (err, doc) {
        if (err) console.log(err)
        if (doc == null) {
            res.json({ auth: false })
        } else {
            next();
        }
    })
}


exports.fileParse = function (req, form, targetDir, cb) {

    form.parse(req, function (err, fields, files) {
        if (err) throw err;
        var filesUrl = [];
        var errCount = 0;
        var keys = Object.keys(files);
        keys.forEach(function (key) {
            if (key == 'file') {
                var filePath = files[key].path;
                var fileExt = filePath.substring(filePath.lastIndexOf('.'));

                //以当前时间戳对上传文件进行重命名
                var fileName = rack() + fileExt;
                var targetFile = path.join(targetDir, fileName);
                //移动文件
                fs.renameSync(filePath, targetFile);
                // 文件的Url（相对路径）
                filesUrl.push('/audio/' + fileName)
                fields.urls = filesUrl
                fields.name = files.file.name
            }

            if (key == 'thumbnail') {
                var filePath = files[key].path;
                var fileExt = filePath.substring(filePath.lastIndexOf('.'));

                //以当前时间戳对上传文件进行重命名
                var fileName = rack() + fileExt;
                var targetFile = path.join(targetDir, fileName);
                //移动文件
                fs.renameSync(filePath, targetFile);
                // 文件的Url（相对路径）
                fields.thumb = '/audio/' + fileName

            }

        })
        cb(fields);
    })
}


exports.imageParse = function (req, form, targetDir, cb) {
    form.parse(req, function (err, fields, files) {
        if (err) throw err;
        var filesUrl = [];
        var errCount = 0;
        var keys = Object.keys(files);
        keys.forEach(function (key) {
            var filePath = files[key].path;
            var fileExt = filePath.substring(filePath.lastIndexOf('.'));

            //以当前时间戳对上传文件进行重命名
            var fileName = rack() + fileExt;
            var targetFile = path.join(targetDir, fileName);
            //移动文件
            fs.renameSync(filePath, targetFile);
            // 文件的Url（相对路径）
            filesUrl.push('/upload/' + fileName)
        })
        fields.urls = filesUrl
        cb(fields);
    })
}
// module.exports = router